﻿using NewRen.Helpers;
using NewRen.Log4net;
using NewRen.Models.DataModel;
using NewRen.Schemas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewRen.Controllers
{
    public class UserApiController : BaseController
    {
        /// <summary>
        ///  接口帮助文档页面
        /// </summary>
        /// <returns></returns>
        //[ValidateSID]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login(string username, string passsword)
        {
            AjaxModel model = new AjaxModel();
            try
            {
                var user = db.Users.Where(u => u.UserName == username && u.Password == Helpers.Encryt.GetMD5(passsword)).FirstOrDefault();
                if (user == null)
                {
                    model.Statu = "err";
                    model.Msg = "用户名或密码不正确！";
                }
                else
                {
                    model.Statu = "ok";
                    model.Data = user;
                }
            }
            catch(Exception ex)
            {
                model.Statu = "err";
                model.Msg = "登录操作出现错误！";
                log.Error(new LogContent("登录接口出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(model);
        }

        /// <summary>
        ///  分页获取用户
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUsers(int page = 0)
        {
            AjaxModel model = new AjaxModel();
            try
            {
                var users = db.Users.Skip(page * 10).Take(10).ToList();
                model.Data = users;
                model.Statu = "ok";
            }
            catch(Exception ex)
            {
                model.Statu = "err";
                model.Msg = "获取失败！";
                log.Error(new LogContent("分页获取用户接口出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(model);
        }


        /// <summary>
        /// 获取首页展示的牛人
        /// </summary>
        /// <returns></returns>
        public ActionResult GetIndexUser()
        {
            AjaxModel model = new AjaxModel();
            try
            {
                var users = db.Users.OrderByDescending(u => u.Priority).Take(10).ToList();
                model.Data = users;
                model.Statu = "ok";
            }
            catch(Exception ex)
            {
                model.Statu = "err";
                model.Msg = "获取失败！";
                log.Error(new LogContent("获取首页展示的牛人接口出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(model);
        }
    }
}